package net.contrend.system.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import net.contrend.system.dao.DeptDao;
import net.contrend.system.form.DeptForm;
import net.contrend.util.BaseAction;

public class DeptAction extends BaseAction {
    
    private DeptDao deptDao;
    
    private void initDao() {
        if (null == this.deptDao) {
            this.deptDao = (DeptDao) this.getBean("deptDao");
        }
    }
    
    public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        DynaActionForm df = (DynaActionForm) form;
        DeptForm dept = (DeptForm) df.get(this.ACTION_FORM_NAME);
        int i = this.deptDao.insert(dept);
        request.setAttribute("ACTION_RESULT", i);
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
    public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        DynaActionForm df = (DynaActionForm) form;
        DeptForm dept = (DeptForm) df.get(this.ACTION_FORM_NAME);
        int i = this.deptDao.update(dept);
        request.setAttribute("ACTION_RESULT", i);
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        String deptId = request.getParameter("deptId");
        int i = this.deptDao.delete(deptId);
        response.getWriter().write(String.valueOf(i));
        
        return null;
    }
    
    public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        String deptId = request.getParameter("deptId");
        DynaActionForm df = (DynaActionForm) form;
        df.set(this.ACTION_FORM_NAME, this.deptDao.query(deptId));
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
}
